<template>
	<view style="position: relative; display: flex; justify-content: center; margin: 0 auto" :style="defineStyle">
		<canvas class="defCanvasClass" :style="defineStyle" canvas-id="defCanvas" id="defCanvas"
			@touchstart.stop="penStart" @touchmove.stop="penMove" @touchend.stop="penEnd"></canvas>

		<image :src="bgImage" :style="defineStyle" v-if="bgImage"></image>
		<view v-else class="img">
			<image :src="uploadImg" :style="uploadStyle" mode="aspectFit"></image>
		</view>
		<canvas class="newCanvasClass" :style="defineStyle" canvas-id="newCanvas" id="newCanvas"></canvas>
		<view :class="['canvasHuabi']"></view>
	</view>
</template>

<script>
	// 绘制点集合
	let drawFigures = [];
	// 保存操作的像素数据
	let imageData = [];
	// 总绘制点的集合
	let totalDrawFigures = [];

	export default {
		data() {
			return {
				curStep: -1, // 当前步数
				myCanvasContext: null,
				// 画布背景图片
				bgImage: null,
				topLeftPoint: {
					// 画布左上角点
					left: 0,
					top: 0,
				},
				// 尺寸
				size: {
					width: 375,
					height: 450,
				},
				// 原图片尺寸
				orgSize: {
					width: 375,
					height: 450,
				},
				startX: 0, // 前一个绘制节点X轴
				startY: 0, // 前一个绘制节点Y轴
				canMaskImg: null,
				blockCanvas: null,
				platform: getApp().globalData.platform, // 平台区分
			};
		},
		props: {
			Image: {
				type: String,
				default: () => {
					return '';
				},
			},
			// 画笔颜色
			lineColor: {
				type: String,
				default: 'rgba(8, 0, 255, 0.1)',
			},
			// 画笔宽度
			lineWidth: {
				type: Number,
				default: 20,
			},
			containerHeight: {
				type: Number,
				default: 450,
			},
			containerWidth: {
				type: Number,
				default: uni.getSystemInfoSync().screenWidth,
			},
			uploadImg: {
				type: String,
				default: 'https://bpic.588ku.com/element_origin_min_pic/19/04/24/850ddb30377bf66e92f68a60f92c827a.jpg',
			},
		},

		watch: {

			Image: {
				handler(newVal) {
					const {
						displayWidth,
						displayHeight,
						imageWidth,
						imageHeight,
						path
					} = this.handleModifySize(
						JSON.parse(newVal)
					);
					this.bgImage = path;
					this.size = {
						width: displayWidth,
						height: displayHeight,
					};
					this.orgSize = {
						width: imageWidth,
						height: imageHeight,
					};
					console.log(this.size, '===>orgSize');
					this.$nextTick(() => {
						this.handleCanvasImg();
					});
				},
				immediate: true,
			},
			bgImage() {
				this.handleCanvasImg();
			},
		},
		computed: {
			defineStyle() {
				return `width:${this.size.width}px;height:${this.size.height}px;`;
			},
		},
		methods: {
			handleInit() {},
			handleCanvasImg() {
				// 获取屏幕信息
				const systemInfo = wx.getSystemInfoSync();
				const screenWidth = systemInfo.screenWidth; // 屏幕宽度(px)

				// 将 rpx 转换为 px
				const rpxToPx = (rpx) => (screenWidth / 750) * rpx;

				// 假设 this.size.width 和 this.size.height 是 rpx 单位的宽高
				const imgWidth = rpxToPx(this.size.width);
				const imgHeight = rpxToPx(this.size.height);
				this.myCanvasContext = uni.createCanvasContext('defCanvas', this);
				// 绘制图片
				this.myCanvasContext.drawImage(this.bgImage, 0, 0, this.size.width, this.size.height);
				let pattern = this.myCanvasContext.createPattern(this.bgImage, 'no-repeat');
				this.myCanvasContext.fillStyle = pattern;
				this.myCanvasContext.draw();

				// 让线条圆润
				this.myCanvasContext.setLineCap('round');
				this.myCanvasContext.strokeStyle = this.lineColor;
				this.myCanvasContext.setFillStyle(this.lineColor);
				this.myCanvasContext.setLineWidth(this.lineWidth);
			},
			beforePenStart(fn, e) {
				const _this = this;
				if (!this.bgImage) {
					this.handleQuShuiYing(fn);
				} else {
					fn(e);
				}
			},
			// penStart
			penStart(e) {
				const _this = this;
				this.beforePenStart(() => {
					console.log(e, '===>131');
					// #ifdef MP-WEIXIN
					const x = e.touches[0].pageX - this.topLeftPoint.left;
					const y = e.touches[0].pageY - this.topLeftPoint.top;
					// #endif
					// #ifndef MP-WEIXIN
					const x = e.changedTouches[0].x;
					const y = e.changedTouches[0].y;
					// #endif
					_this.myCanvasContext && _this.myCanvasContext.beginPath();
					_this.startX = x;
					_this.startY = y;
					console.log(x, y, drawFigures, '===>142');
					_this.drawCurve(x, y);
					if (!Array.isArray(drawFigures)) {
						drawFigures = [];
					}
					drawFigures = drawFigures.filter((figure, index) => index <= _this.curStep);
					console.log(x, y, drawFigures, '===>148');
					drawFigures.push({
						lineColor: _this.lineColor,
						lineWidth: _this.lineWidth,
						points: [{
							x,
							y,
						}, ],
					});
				}, e);
			},
			/**
			 * 滑动事件
			 * @param {Object} e
			 */
			penMove(e) {
				if (this.platform != 'ios') {
					if (!this.bgImage) return;
					if (this.intervalId) {
						clearInterval(this.intervalId);
						this.intervalId = null;
					}
					this.intervalId = setInterval((_) => (this.canDraw = true), 100);
					// #ifdef MP-WEIXIN
					const x = e.mp.touches[0].x;
					const y = e.mp.touches[0].y;
					// #endif
					// #ifdef MP-QQ
					let x, y;
					if (this.platform == 'ios') {
						x = e.touches[0].x;
						y = e.touches[0].y;
					} else {
						x = e.touches[0].clientX;
						y = e.touches[0].clientY;
					}
					// #endif
					// #ifndef MP-WEIXIN || MP-QQ
					const x = e.touches[0].x;
					const y = e.touches[0].y;
					// #endif
					this.addToPoints(x, y);
					this.drawCurve(x, y);
					this.myCanvasContext.draw(true);
				} else {
					if (!this.bgImage) return;
					if (this.intervalId) {
						clearInterval(this.intervalId);
						this.intervalId = null;
					}
					this.intervalId = setInterval((_) => (this.canDraw = true), 100);
					// #ifdef MP-WEIXIN
					const x = e.mp.touches[0].x;
					const y = e.mp.touches[0].y;
					// #endif
					// #ifndef MP-WEIXIN
					const x = e.touches[0].x;
					const y = e.touches[0].y;
					// #endif
					this.addToPoints(x, y);
					this.drawCurve(x, y);
					this.myCanvasContext.draw(true);
				}
			},
			// 重新上传图片
			resetImg() {
				let _this = this;
				uni.chooseImage({
					sizeType: ['compressed', 'original'],
					count: 1,
					success: (img) => {
						uni.getImageInfo({
							src: img.tempFilePaths[0],
							success: (res) => {
								const containerWidth = uni.getSystemInfoSync().screenWidth;
								const containerHeight = this.containerHeight;
								const imageWidth = res.width;
								const imageHeight = res.height;
								const aspectRatio = imageWidth / imageHeight;
								let displayWidth, displayHeight;
								if (containerWidth / containerHeight > aspectRatio) {
									displayHeight = containerHeight;
									displayWidth = containerHeight * aspectRatio;
								} else {
									displayWidth = containerWidth;
									displayHeight = containerWidth / aspectRatio;
								}
								this.bgImage = res.path;
								this.size = {
									width: displayWidth,
									height: displayHeight,
								};
								this.orgSize = {
									width: imageWidth,
									height: imageHeight,
								};
								console.log(this.size, this.orgSize, '112');
							},
						});
					},
				});
			},
			/**
			 * 添加到点数组
			 * @param {Object} x
			 * @param {Object} y
			 */
			addToPoints(x, y) {
				if (!this.bgImage) return;
				const drawFigure = drawFigures[this.curStep + 1];
				drawFigure.points.push({
					x,
					y,
				});
				if (drawFigure.points.length == 1) {
					drawFigure.points.push({
						x,
						y,
					});
				} else {
					drawFigure.points[1] = {
						x,
						y,
					};
				}
				return drawFigures;
			},
			handleModifySize(res) {
				// #ifdef MP-ALIPAY
				const containerWidth = uni.getSystemInfoSync().screen.width;
				// #endif
				// #ifndef MP-ALIPAY
				const containerWidth = uni.getSystemInfoSync().screenWidth;
				// #endif

				// const containerHeight = 600;
				// const imageWidth = res.width;
				// const imageHeight = res.height;
				// const aspectRatio = imageWidth / imageHeight;
				// let displayWidth, displayHeight;

				// if (containerWidth / containerHeight > aspectRatio) {
				// 	displayHeight = containerHeight;
				// 	displayWidth = containerHeight * aspectRatio;
				// } else {
				// 	displayWidth = containerWidth;
				// 	displayHeight = containerWidth / aspectRatio;
				// }
				//    console.log(displayHeight);
				// return {
				// 	displayWidth,
				// 	displayHeight,
				// 	imageWidth,
				// 	imageHeight,
				// 	path: res.path,
				// };
				// clog;
				const containerHeight = 500; // 固定高度
				const maxWidth = containerWidth; // 最大宽度限制为 375rpx
				const imageWidth = res.width;
				const imageHeight = res.height;
				const aspectRatio = imageWidth / imageHeight; // 图片宽高比

				// 固定高度，自适应宽度
				let displayHeight = containerHeight; // 高度固定
				let displayWidth = containerHeight * aspectRatio; // 宽度根据高度自适应

				// 如果计算出的宽度大于最大宽度限制，则进行调整
				if (displayWidth > maxWidth) {
					displayWidth = maxWidth; // 限制宽度
					displayHeight = maxWidth / aspectRatio; // 根据宽度调整高度，保持宽高比
				}

				return {
					displayWidth, // 计算后的显示宽度
					displayHeight, // 计算后的显示高度
					imageWidth, // 原始图片宽度
					imageHeight, // 原始图片高度
					path: res.path, // 图片路径
				};
			},
			handleQuShuiYing(fn) {
				let _this = this;
				uni.chooseImage({
					sizeType: ['compressed', 'original'],
					count: 1,
					success: (img) => {
						uni.getImageInfo({
							src: img.tempFilePaths[0],
							success: (res) => {
								const {
									displayWidth,
									displayHeight,
									imageWidth,
									imageHeight,
									path
								} = this.handleModifySize(res);
								this.bgImage = path;
								this.size = {
									width: displayWidth,
									height: displayHeight,
								};
								this.orgSize = {
									width: imageWidth,
									height: imageHeight,
								};
								this.$nextTick(() => {
									fn();
								});
							},
						});
					},
				});
			},
			// 画出
			drawCurve(x, y) {
				this.myCanvasContext && this.myCanvasContext.beginPath();
				this.myCanvasContext.moveTo(this.startX, this.startY);
				this.myCanvasContext.strokeStyle = this.lineColor;
				this.myCanvasContext.setLineWidth(this.lineWidth)
				this.myCanvasContext.lineTo(x, y);
				this.myCanvasContext.stroke();
				this.startX = x;
				this.startY = y;
			},
			/**
			 * 离开屏幕事件
			 * @param {Object} e
			 */
			penEnd(e) {
				// #ifdef MP-WEIXIN
				const x = e.changedTouches[0].pageX - this.topLeftPoint.left;
				const y = e.changedTouches[0].pageY - this.topLeftPoint.top;
				// #endif
				// #ifndef MP-WEIXIN
				const x = e.changedTouches[0].x;
				const y = e.changedTouches[0].y;
				// #endif
				const totalPoints = this.addToPoints(x, y);
				totalDrawFigures.push(...totalDrawFigures, ...totalPoints);
				this.drawCurve(x, y);
				// this.handleTotalPoints(totalDrawFigures);
			},
			// 处理totalPoints
			handleTotalPoints(regions = totalDrawFigures) {
				if (regions.length <= 0) {
					return
				}
				this.blockCanvas = uni.createCanvasContext('newCanvas', this);
				// 设置画布为黑色背景
				this.blockCanvas.setFillStyle('black');
				this.blockCanvas.fillRect(0, 0, this.size.width, this.size.height);
				this.blockCanvas.setStrokeStyle('white');
				this.blockCanvas.setLineJoin('round'); // 使线条连接处更平滑
				this.blockCanvas.setLineCap('round'); // 使线条末端更平滑

				// 遍历每段路径并绘制
				regions.forEach((region) => {
					this.blockCanvas.setLineWidth(region.lineWidth);
					const points = region.points || [];
					this.blockCanvas.beginPath();
					this.blockCanvas.moveTo(points[0].x, points[0].y);
					for (let i = 1; i < points.length; i++) {
						this.blockCanvas.lineTo(points[i].x, points[i].y);
					}
					this.blockCanvas.stroke();
				});
				return new Promise((resolve, resject) => {

					this.blockCanvas.draw(
						false,
						() => {
							uni.canvasToTempFilePath({
									canvasId: 'newCanvas',
									width: this.size.width,
									height: this.size.height,
									fileType: 'png',
									destWidth: this.orgSize.width, // 生成图片的实际宽度，可以放大或缩小
									destHeight: this.orgSize.height, // 生成图片的实际高度
									success: (res) => {
										// 将 imageData 发送给后端或返回
										resolve()
										this.canMaskImg = res.tempFilePath;
									},
									fail: function(err) {
										console.log(err);
									},
								},
								this
							);
						},
						this
					);
				})
			},
			// 重置操作
			redo() {
				this.myCanvasContext.clearRect(0, 0, parseInt(this.size.width * 2) / 2, parseInt(this.size.height * 2) /
				2);
				drawFigures = [];
				imageData = [];
				totalDrawFigures = [];
				this.curStep = -1;
				this.myCanvasContext.draw(true);
				this.canMaskImg = null;
			},
			/**
			 * 保存画布内容
			 */
			saveCanvas() {
				if (!this.bgImage) {
					this.penStart();
					return;
				}
				const _that = this;
				return new Promise((resolve, reject) => {
					// 定时器线程中执行绘制，否则因绘制占用主线程导致加载动画不显示
					if (this.canMaskImg && this.bgImage) {
						resolve({
							maskImg: this.canMaskImg,
							orgImg: this.bgImage,
						});
					} else {
						reject('请擦抹需要去水印的位置~');
					}
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.newCanvasClass {
		position: absolute;

		/* #ifndef MP-WEIXIN */
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		visibility: hidden;
		z-index: -99999999;
		/* #endif */
		/* #ifdef MP-WEIXIN */
		left: 5000%;
		/* #endif */
	}

	.img {
		position: absolute;
		z-index: 1;
	}

	.defCanvasClass {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		z-index: 2;
	}
</style>